package com.lianyi.login.mvp.presenter;

import android.app.Application;
import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.OnLifecycleEvent;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.android.arouter.launcher.ARouter;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import okhttp3.ResponseBody;

import javax.inject.Inject;

import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.PermissionUtil;
import com.jess.arms.utils.RxLifecycleUtils;
import com.lianyi.commonsdk.core.RouterHub;
import com.lianyi.commonsdk.util.ARouterUtils;
import com.lianyi.commonsdk.util.LogUtil;
import com.lianyi.commonsdk.util.MD5Util;
import com.lianyi.commonsdk.util.NetworkUtils;
import com.lianyi.commonsdk.util.SPUtils;
import com.lianyi.commonsdk.util.SPUtilsName;
import com.lianyi.commonsdk.util.ToastUtil;
import com.lianyi.commonsdk.util.security.AESOperator;
import com.lianyi.commonsdk.util.security.AesUtils;
import com.lianyi.commonsdk.util.security.RSAEncryptor;
import com.lianyi.commonsdk.util.security.RsaUtils;
import com.lianyi.login.mvp.contract.LoginContract;
import com.lianyi.login.mvp.ui.activity.DoctorListActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.List;


@ActivityScope
public class LoginPresenter extends BasePresenter<LoginContract.Model, LoginContract.View> {
    private RxErrorHandler mErrorHandler;
    private Application mApplication;
    private ImageLoader mImageLoader;
    private AppManager mAppManager;

    @Inject
    public LoginPresenter(LoginContract.Model model, LoginContract.View rootView
            , RxErrorHandler handler, Application application
            , ImageLoader imageLoader, AppManager appManager) {
        super(model, rootView);
        this.mErrorHandler = handler;
        this.mApplication = application;
        this.mImageLoader = imageLoader;
        this.mAppManager = appManager;
    }

    /**
     * 使用 2017 Google IO 发布的 Architecture Components 中的 Lifecycles 的新特性 (此特性已被加入 Support library)
     * 使 {@code Presenter} 可以与 {@link android.support.v4.app.SupportActivity} 和 {@link Fragment} 的部分生命周期绑定
     */
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    void onCreate() {
//        requestUsers();//打开 App 时自动加载列表
    }

    public void requestUsers(String account, String password) {
        //请求外部存储权限用于适配android6.0的权限管理机制
        PermissionUtil.externalStorage(new PermissionUtil.RequestPermission() {
            @Override
            public void onRequestPermissionSuccess() {

            }

            @Override
            public void onRequestPermissionFailure(List<String> permissions) {
                mRootView.showMessage("Request permissions failure");
            }

            @Override
            public void onRequestPermissionFailureWithAskNeverAgain(List<String> permissions) {
                mRootView.showMessage("Need to go to the settings");
            }
        }, mRootView.getRxPermissions(), mErrorHandler);
        if (TextUtils.isEmpty(account)) {
            ToastUtil.showShortToast("登录账号不能为空！");
        } else if (TextUtils.isEmpty(password)) {
            ToastUtil.showShortToast("密码不能为空！");
        } else {
            if (NetworkUtils.isConnected()) {
//                mModel.getRsa()
//                        .subscribeOn(Schedulers.io())
//                        .observeOn(AndroidSchedulers.mainThread())
//                        .doOnSubscribe(new Consumer<Disposable>() {
//                            @Override
//                            public void accept(Disposable disposable) throws Exception {
//                                mRootView.showLoading();
//                            }
//                        })
//                        .doOnNext(new Consumer<ResponseBody>() {
//                            @Override
//                            public void accept(ResponseBody responseBody) throws Exception {
//                                try {
//                                    String mDate = responseBody.string();
//                                    Log.e("111", mDate + "==");
//                                    try {
//                                        if (responseBody != null && !TextUtils.isEmpty(mDate)) {
//                                            JSONObject object = new JSONObject(mDate);
//                                            mDate = object.getString("data");
//                                            String msg = object.getString("msg");
//                                            String result = object.getString("result");
//                                            if ("success".equals(result)) {
//                                                AESOperator myAESO = new AESOperator();
//                                                try {
//                                                    mDate = myAESO.decrypt(mDate);
//                                                    LogUtil.e("mDate", "mDate" + mDate);
//                                                    JSONObject object1 = new JSONObject(mDate);
//                                                    String rsa = object1.getString("rsa");
//                                                    String aes = object1.getString("aes");
//                                                    LogUtil.e("获取aes", rsa + "||" + aes);
//                                                    SPUtils.getInstance(SPUtilsName.HOSPITAL_TABLE).put(SPUtilsName.HOSPITAL_RSA, rsa);
//                                                    SPUtils.getInstance(SPUtilsName.HOSPITAL_TABLE).put(SPUtilsName.HOSPITAL_AES, aes);
//                                                } catch (Exception e) {
//                                                    e.printStackTrace();
//                                                }
//                                            } else {
//                                                mRootView.showMessage(msg);
//                                            }
//                                        } else {
//                                            LogUtil.e("JSONObject为空", "JSONObject为空");
//                                        }
//                                    } catch (JSONException e) {
//                                        e.printStackTrace();
//                                    }
//                                } catch (IOException e) {
//                                    e.printStackTrace();
//                                }
//
//                            }
//                        })
//                        .observeOn(Schedulers.io())
//                        .flatMap(new Function<ResponseBody, ObservableSource<ResponseBody>>() {
//                            @Override
//                            public ObservableSource<ResponseBody> apply(ResponseBody responseBody) throws Exception {
//                                try {
//                                    String mDate = responseBody.string();
//                                    LogUtil.e("flatMap", mDate + "==");
//                                } catch (IOException e) {
//                                    e.printStackTrace();
//                                }
//                                JSONObject jsonObject = new JSONObject();
//                                jsonObject.put("passwd", MD5Util.MD5(password));
//                                String account_name = RsaUtils.ResDecode(account);
//                                String json = RsaUtils.ResDecode(jsonObject.toString());
//                                return mModel.login(account_name, json);
//                            }
//                        })
//                        .observeOn(AndroidSchedulers.mainThread())
//                        .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
//                        .doFinally(new Action() {
//                            @Override
//                            public void run() throws Exception {
//                                mRootView.hideLoading();
//                            }
//                        })
//                        .subscribe(new Observer<ResponseBody>() {
//                            @Override
//                            public void onSubscribe(Disposable d) {
//
//                            }
//
//                            @Override
//                            public void onNext(ResponseBody responseBody) {
//                                try {
//                                    String mDate = responseBody.string();
//                                    if (!TextUtils.isEmpty(mDate)) {
//                                        try {
//                                            JSONObject object = new JSONObject(mDate);
//                                            String result = object.getString("result");
//                                            String msg = object.getString("msg");
//                                            if ("success".equals(result)) {
//                                                mDate = AesUtils.AesDecode(object.getString("data"));
//                                                LogUtil.e("222", mDate + "==");
//                                                JSONArray jsonArray = new JSONArray(mDate);
//                                                JSONObject jsonObject = jsonArray.getJSONObject(0);
//                                                int hid = jsonObject.getInt("id");
//                                                SPUtils.getInstance(SPUtilsName.HOSPITAL_TABLE).put(SPUtilsName.HOSPITAL_HID, hid);
//                                                String Rsatr = SPUtils.getInstance(SPUtilsName.HOSPITAL_TABLE).getString(SPUtilsName.HOSPITAL_RSA);
//                                                RSAEncryptor rsaEncryptor = null;
//                                                String data = "";
//                                                try {
//                                                    Rsatr = Rsatr.replace("\n", "\r");
//                                                    String json = "{\"hospitalid\":\"" + hid + "\"}";
//                                                    data = rsaEncryptor.encryptByPublic(json, Rsatr); // RAS加密提交
//                                                } catch (Exception e) {
//                                                    // TODO Auto-generated catch block
//                                                    e.printStackTrace();
//                                                }
//                                                getDoctorList(hid, data);
//                                            } else {
//                                                mRootView.showMessage(msg);
//                                            }
//                                        } catch (JSONException e) {
//                                            e.printStackTrace();
//                                        }
//                                    }
//                                } catch (IOException e) {
//                                    e.printStackTrace();
//                                }
//                            }
//
//                            @Override
//                            public void onError(Throwable e) {
//                                LogUtil.e("onError:", e.getMessage() + "==");
//                                if (e instanceof ConnectException) {
//                                    LogUtil.e("onError:", "没有网络连接!");
//                                } else if (e instanceof SocketTimeoutException) {
//                                    LogUtil.e("onError:", "网络连接超时!");
//                                }
//                                mRootView.showMessage("网络错误:" + e);
//                            }
//
//                            @Override
//                            public void onComplete() {
//                                LogUtil.e("onComplete:", "onComplete");
//                            }
//                        });
                mModel.getRsa()
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<ResponseBody>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(ResponseBody responseBody) {
                                try {
                                    String mDate = responseBody.string();
                                    LogUtil.e("onNext:", mDate + "==");
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                                LogUtil.e("onError:", e.getMessage() + "==");
                                if (e instanceof ConnectException) {
                                    LogUtil.e("onError:", "没有网络连接!");
                                } else if (e instanceof SocketTimeoutException) {
                                    LogUtil.e("onError:", "网络连接超时!");
                                }
                                mRootView.showMessage("网络错误:" + e);
                            }

                            @Override
                            public void onComplete() {
                                LogUtil.e("onComplete:", "onComplete");
                            }
                        });


            } else {
                mRootView.showMessage("请连接网络!");
            }
        }
    }

    private void getDoctorList(int hid, String data) {
        mModel.getDoctorList(hid, data)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        try {
                            String mDate = responseBody.string();
                            if (!TextUtils.isEmpty(mDate)) {
                                try {
                                    JSONObject object = new JSONObject(mDate);
                                    String result = object.getString("result");
                                    String msg = object.getString("msg");
                                    if ("success".equals(result)) {
                                        mDate = AesUtils.AesDecode(object.getString("data"));
                                        LogUtil.e("医生列表", mDate + "==");
                                        SPUtils.getInstance(SPUtilsName.HOSPITAL_TABLE).put(SPUtilsName.DOUCTOR_ALL, mDate);
//                                        Intent intent = new Intent(mRootView.getActivity(), DoctorListActivity.class);
//                                        intent.putExtra(DoctorListActivity.DOCTOR_LIST_ALL, mDate);
                                        ARouter.getInstance().build(RouterHub.LOGIN_DOCTORLISTACTIVITY)
                                                .withString(DoctorListActivity.DOCTOR_LIST_ALL, mDate)
                                                .navigation(mRootView.getActivity());
//                                        mRootView.launchActivity(intent);
                                    } else {
                                        mRootView.showMessage(msg);
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtil.e("getDoctorList onError:", e.getMessage() + "==");
                        mRootView.showMessage("网络错误:" + e);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

}
